package methodcompose
class FruitMarket {
    def buyApple(){ println "buy Apple" }
    //约定的其他水果
    def others=["Banana","Melon"]
    //拦截对不存在方法调用
    def methodMissing(String name,def args) {
        //根据约定推断语义,动态合成方法
        def result = others.find { it == name.split("buy")[1] }
        if(result){//有约定,动态合成逻辑
            println "方法合成"
            def method ={
                println "buy ${name.split("buy")[1]}"
            }
            //将方法注入实例,以后直接调用,避免每次合成(即缓存)
            FruitMarket instance = this
            instance.metaClass."$name"=method //不能直接用this
            method(args) //调用方法
        }else{
            throw new MissingMethodException(name,FruitMarket.class,args)
        }
    }
    static void main(String[] args) {
        def market = FruitMarket.newInstance()
        market.buyApple()
        market.buyBanana() //调用不存在方法
        market.buyBanana() //第二次调用
        market.buyHaha()
    }
}
